package moe.hotk.controller

import java.util.{List => JList}

import com.typesafe.scalalogging.LazyLogging
import moe.hotk.common._
import moe.hotk.entity._
import moe.hotk.repository._
import org.springframework.http._
import org.springframework.web.bind.annotation._

import scala.collection.JavaConverters._
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

@RestController
class TruthController extends LazyLogging {

  @GetMapping(Array("/api/truths"))
  def getTruths: JList[Truth] = {
    logger debug "GET /api/truths"
    Truths.getAll.asJava
  }

  @GetMapping(Array("/api/truth"))
  def getTruthById(@RequestParam id: Long): ResponseEntity[String] = {
    logger debug s"GET /api/truth $id"
    Truths getOneById id match {
      case Some(truth) => returnJson(truth)
      case None => returnJson(Map("message" -> "not found"), HttpStatus.NOT_FOUND)
    }
  }

  @PostMapping(Array("/api/truth"))
  def postTruth(@RequestBody truth: Truth): ResponseEntity[String] = {
    logger debug s"POST /api/truth $truth"
    Truths create truth
    success
  }

  @PutMapping(Array("/api/truth"))
  def putTruth(@RequestBody truth: Truth): ResponseEntity[String] = {
    logger debug s"PUT /api/truth $truth"
    Truths update truth
    success
  }

  @DeleteMapping(Array("/api/truth"))
  def deleteTruth(@RequestParam id: Long): ResponseEntity[String] = {
    logger debug s"DELETE /api/truth $id"
    Truths delete id
    success
  }

  private lazy val success = returnJson(Map())

  private def returnJson[A: TypeTag : ClassTag](
    content: A,
    status: HttpStatus = HttpStatus.OK,
  ) = new ResponseEntity(
    Json stringify content,
    new HttpHeaders withSideEffect (_ setContentType MediaType.APPLICATION_JSON_UTF8),
    status
  )

}
